package com.linyu.linpicturebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linyu.linpicturebackend.annotation.AuthCheck;
import com.linyu.linpicturebackend.common.base.BaseResponse;
import com.linyu.linpicturebackend.common.base.DeleteRequest;
import com.linyu.linpicturebackend.common.exception.BusinessException;
import com.linyu.linpicturebackend.common.exception.ErrorCode;
import com.linyu.linpicturebackend.common.utils.ResultUtils;
import com.linyu.linpicturebackend.common.utils.ThrowUtils;
import com.linyu.linpicturebackend.constant.UserConstant;
import com.linyu.linpicturebackend.model.dto.user.UserAddRequest;
import com.linyu.linpicturebackend.model.dto.user.UserLoginRequest;
import com.linyu.linpicturebackend.model.dto.user.UserQueryRequest;
import com.linyu.linpicturebackend.model.dto.user.UserRegisterRequest;
import com.linyu.linpicturebackend.model.dto.user.UserUpdateRequest;
import com.linyu.linpicturebackend.model.entity.User;
import com.linyu.linpicturebackend.model.vo.LoginUserVO;
import com.linyu.linpicturebackend.model.vo.UserVO;
import com.linyu.linpicturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * MainController 测试类
 *
 * @author liyang
 * @since 2024/12/15 23:56
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userRegisterRequest 账号密码信息
     * @return 用户id
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(userService.userRegister(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(), userRegisterRequest.getCheckPassword()));
    }


    /**
     * 用户登录
     * @param userLoginRequest 账号密码
     * @param request 请求
     * @return 用户脱敏信息
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(userService.userLogin(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword(), request));
    }

    /**
     * 获取当前登录用户信息（脱敏）
     * @param request 请求
     * @return 获取当前登录用户信息（脱敏）
     */
    @ApiOperation("获取当前登录用户信息（脱敏）")
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request){
        return ResultUtils.success(userService.getLoginUserVO(userService.getLoginUser(request)));
    }

    /**
     * 用户注销
     * @param request 请求
     * @return 请求结果
     */
    @ApiOperation("用户注销")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(userService.userLogout(request));
    }

    /**
     * 创建用户
     * @param userAddRequest 用户信息
     * @return 用户id
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("创建用户")
    @PostMapping("/add")
    public BaseResponse<Long> userAuthRegister(@RequestBody UserAddRequest userAddRequest){
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码
        final String DEFAULT_PASSWORD = "12345678";
        user.setUserPassword(userService.getEncryptPassword(DEFAULT_PASSWORD));
        // 插入数据库
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据id获取用户
     * @param id 用户id
     * @return 用户信息
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("根据id获取用户")
    @GetMapping("/get")
    public BaseResponse<User> getUserById(long id){
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据id获取用户脱敏信息
     * @param id 用户id
     * @return 用户脱敏信息
     */
    @ApiOperation("根据id获取用户脱敏信息")
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id){
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     * @param deleteRequest 被删除用户的信息
     * @return 删除结果
     */
    @ApiOperation("删除用户")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }


    /**
     * 更新用户
     * @param userUpdateRequest 更新请求
     * @return 更新结果
     */
    @ApiOperation("更新用户")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     * @param userQueryRequest 查询请求参数
     */
    @ApiOperation("分页获取用户封装列表（仅管理员）")
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getLambdaQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

}